package org.budo.graph.view.util;

import java.util.Map;

import org.budo.ehcache.config.annotation.entity.EhCacheConfigEntity;
import org.budo.graph.service.util.EhcacheStatisticsUtil;
import org.budo.support.spring.context.aware.BudoApplicationContextAware;
import org.budo.support.spring.util.SpringUtil;
import org.springframework.context.ApplicationContext;

import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.CacheManager;

/**
 * @author limingwei
 */
@Slf4j
public class EhcacheGraphUtil {
    private static CacheManager _cacheManager;

    public static CacheManager getCacheManager() {
        if (null != _cacheManager) {
            return _cacheManager;
        }

        BudoApplicationContextAware applicationContextAware = BudoApplicationContextAware.getInstance();
        if (null == applicationContextAware) {
            log.warn("#51 BudoApplicationContextAware is null");
            return null;
        }

        ApplicationContext applicationContext = applicationContextAware.getApplicationContext();
        if (null == applicationContext) {
            log.warn("#57 applicationContext is null, applicationContextAware=" + applicationContextAware);
            return null;
        }

        _cacheManager = SpringUtil.getBean(applicationContext, CacheManager.class);
        if (null == _cacheManager) {
            log.warn("#63 cacheManager is null, applicationContext=" + applicationContext);
            return null;
        }

        return _cacheManager;
    }

    /**
     * 开关是否打开
     */
    public static boolean isCacheGraphOpen(String cacheName) {
        Map<String, EhCacheConfigEntity> cacheConfigMap = EhcacheStatisticsUtil.getEhCacheConfigEntityMap();
        if (null == cacheConfigMap) {
            return false;
        }

        EhCacheConfigEntity configEntity = cacheConfigMap.get(cacheName);
        if (null == configEntity) {
            return false;
        }

        Boolean graph = configEntity.getGraph();
        return null != graph && graph;
    }

}